package AliDiepPR.hWriting;

import android.content.*;
import android.graphics.*;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.*;
import java.util.*;

public class WriteView extends View {

	private ArrayList<Path> paths;
	private ArrayList<PointF> points;
	private Paint paint;
	private Path currentPath;
	private float oldX, oldY;
	private boolean isPaused;

	private void setup() {
		resetView();
		paint = new Paint();
		paint.setColor(Color.BLACK);
		paint.setAntiAlias(true);
		paint.setDither(true);
		paint.setStyle(Style.STROKE);
		//paint.setStrokeCap(Cap.ROUND);
		//paint.setStrokeJoin(Join.ROUND);
		paint.setStrokeWidth(5);
		this.setDrawingCacheBackgroundColor(Color.WHITE);
		this.setDrawingCacheEnabled(true);
	}

	public void resetView() {
		oldX = 0;
		oldY = 0;
		currentPath = null;
		paths = new ArrayList<Path>();
		points = new ArrayList<PointF>();
	}

	public WriteView(Context context) {
		super(context);
		setup();
	}

	public WriteView(Context context, AttributeSet att) {
		super(context, att);
		setup();
	}

	public WriteView(Context context, AttributeSet att, int i) {
		super(context, att, i);
		setup();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawColor(Color.WHITE);

		if (paths != null && points != null) {
			for (Path path : paths) {
				if (path != null) {
					canvas.drawPath(path, paint);
				}
			}

			for (PointF point : points) {
				canvas.drawPoint(point.x, point.y, paint);
			}
		}

	}

	public Bitmap getImage() {
		this.setDrawingCacheEnabled(true);   
		/*
		this.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
		            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		this.layout(0, 0, this.getMeasuredWidth(), this.getMeasuredHeight()); 
		*/
		this.buildDrawingCache(true);
		Bitmap result = Bitmap.createBitmap(getDrawingCache());
		this.setDrawingCacheEnabled(false);
		return result;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:

			currentPath = new Path();
			currentPath.moveTo(x, y);
			oldX = x;
			oldY = y;
			paths.add(currentPath);
			invalidate();
			isPaused = false;
			break;

		case MotionEvent.ACTION_MOVE:
			if ((Math.abs(x - oldX) > 0) || (Math.abs(y - oldY) > 0)) {
				currentPath.quadTo(oldX, oldY, (oldX + x) / 2, (oldY + y) / 2);
				oldX = x;
				oldY = y;
			}
			invalidate();
			break;

		case MotionEvent.ACTION_UP:
			currentPath.lineTo(oldX, oldY);
			if ((x == oldX) && (y == oldY)) {
				points.add(new PointF(x, y));
			}
			invalidate();
			isPaused = true;

			break;
		}
		return true;
	}

}
